# 类似于django里的 path + 视图函数
# APIRouter 用于定义多个路由接口，并可以将它们组织成模块化、可复用的部分。
from fastapi import APIRouter
from models import Book, Author, Publish

# 生成路由对象，入口main.py中注册
api_book = APIRouter()

@api_book.get('/info')
async def index():
    books = await Book.all().prefetch_related('authors').select_related('publishes')
    book_data_list = [
        {
            # "id": book.id,
            "title": book.title,
            "price": book.price,
            "img_url": book.img_url,
            "bread": book.bread,
            "bcomment": book.bcomment,
            "publish": {
                "id": book.publishs.id,
                "name": book.publishes.name,
                "email": book.publishes.email
            },
            "authors": [
                {
                    "id": author.id,
                    "name": author.name,
                    "age": author.age
                }
                for author in book.authors
            ]
        }
        for book in books
    ]
    return {"code": 200, "data": book_data_list}